<?php
declare(strict_types=1);

namespace Service\HanshowService;

use Service\Code\Normal;
use Service\BaseService;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Amqp\Producer;
use Service\Code\CodeBuilder;
use App\Amqp\Producer\HanshowMessageProducer;
use Service\GoodsService\ChannelGoodsService;
use Service\GoodsService\MnGoodsService;
use Service\UserService\MnUserService;
use App\Model\BbcModel\Goods;
use Service\VenderClient\Hanshow\HanshowApi;
use App\Model\BbcModel\MnQrcode;
use App\Model\BbcModel\MnUrllink;

class HanshowService extends BaseService
{
    /**
     * 发布消息队列
     * @param array $msg
     */
    public function publishMsg( array $msg  = [] )
    {
        try {
            $handlerMessage = new HanshowMessageProducer($msg);
            $producer = ApplicationContext::getContainer()->get(Producer::class);
            $result = $producer->produce($handlerMessage,true);
            if( $result ) {
                return Normal::returnCode(Normal::SUC,"发布成功");
            }
            return Normal::returnCode(Normal::FAIL,"操作失败，请稍微再试[100000]");
        } catch ( \Throwable $e ) {
            return Normal::returnCode(Normal::FAIL,"操作失败，请稍微再试[{$e->getMessage()},{$e->getLine()},{$e->getFile()}]");
        }
    }
    
    public function consumerMessage(array $param ) { 
        $config=$param['config'];
        $goodsIds=$param['goodsIds'];
        $mn_sid=$param['mn_sid'];
        $mn_user    = MnUserService::getMnUserInfoByMnSid($mn_sid);
        $mn_user_type = $mn_user['type'];
        $mn_level     = $mn_user['level'];
        $select = [
            'g.*',
            'gc.name as classname',
            'gb.name as brandname',
            'msg.quantity',
            'msg.storestatus'
        ];
        $table = Goods::instance()->getTable();
        $list = Goods::instance()
        ->from("{$table} as g")
        ->select($select)
        ->leftjoin('ly_mn_store_goods as msg','msg.goods_id','=','g.id')
        ->leftjoin('ly_goods_class as gc','gc.id','=','g.class_id')
        ->leftjoin('ly_goods_brand as gb','gb.id','=','g.brand_id')
        ->where('msg.mn_sid',$mn_sid)
        ->whereIn('g.id',$goodsIds)->get()->toArray();
        $profitGoodsPriceLists = MnGoodsService::instance()->getGoodsAllProfit($mn_sid, $goodsIds,1,$mn_level);
        $profitGoodsPriceListMap = array_column($profitGoodsPriceLists,null,'goods_id');
        $datas=[];
//        $mnqrcode= MnQrcode::instance()->where('basegoods',1)->where('mnid',4)->where('mn_sid',$mn_sid)->whereIn('belong_id',$goodsIds)->get()->toArray();
//        $qrcodeMap= array_column($mnqrcode, 'img','belong_id');
        $mnurllink= MnUrllink::instance()->where('mn_sid',$mn_sid)->whereIn('goods_id',$goodsIds)->get()->toArray();
        $qrcodeMap= array_column($mnurllink, 'mn_urllink','goods_id');
        foreach ($list as $key => $value) {
            $goods_id               = $value['id'];
            $profit                 = $profitGoodsPriceListMap[$goods_id] ?? [];
            $value['price_store']   = $profit['price_store'] ?? '0.00';
            $price                  = bcadd((string)$value['price_store'],(string)$profit['profit']?? '0.00',2);
            $price_vip              = bcadd((string)$value['price_store'],(string)$profit['profit_vip']?? '0.00',2);
            $price_tax              =0;
            $price_vip_tax          =0;
            $price_total            =$price;
            $price_vip_total        =$price_vip;
            if( $value['is_bonded']==1) 
            {
                if( $value['tax_free']== 0 ) {
                    $price_tax          = bcmul((string)$price, (string)$value['tax_rate'],3);
                    $price_vip_tax      = bcmul((string)$price_vip, (string)$value['tax_rate'],3);
                    $price_tax          = number_format((float)$price_tax,2,'.','');
                    $price_vip_tax      = number_format((float)$price_vip_tax,2,'.','');
                    $price_total        = bcadd((string)$price_tax, (string)$price,2);
                    $price_vip_total    = bcadd((string)$price_vip_tax,(string) $price_vip,2);
                }else{
                    $taxflag            = bcadd('1', (string)$value['tax_rate'],3);
                    $price              = bcdiv((string)$price, (string)$taxflag, 3);
                    $price_vip          = bcdiv((string)$price_vip, (string)$taxflag, 3);
                    $price              = number_format((float)$price,2,'.','');
                    $price_vip          = number_format((float)$price_vip,2,'.','');
                    $price_tax          = bcsub((string)$price_total, (string)$price,2);
                    $price_vip_tax      = bcsub((string)$price_vip_total, (string)$price_vip,2);
                }
            }
            $datas[]=[
                'Id'=>$goods_id,
                'sku'=>$value['skucode'],
                'itemName'=>$value['name'],
                'price1'=>$price_total,
                'Price1Description'=>'零售价',
                'price3'=>$price_vip_total,
                'price3Description'=>'会员价',
                'ean'=>$value['barcode'],
                'itemStatus'=>$value['storestatus']==1?'销售中':"下架中",
                'brand'=>$value['brandname'],
                'placeOfOrigin'=>$value['origin'],
                'unit'=>$value['unit_name'],
                'level3CategoryName'=>$value['classname'],
                'inventory'=>$value['quantity'],
                'qrCode'=>$qrcodeMap[$goods_id]??''
            ];
        }
        return (new HanshowApi($config))->UpdateGoods($mn_sid, $datas);
    }
}
